#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>

WiFiClient client;
PubSubClient mqtt(client);

void mqtt_callback(const char* topic, byte* payload, unsigned int length)
{
    const size_t capacity = JSON_OBJECT_SIZE(1) + 20;
    DynamicJsonDocument doc(capacity);

    deserializeJson(doc, payload, length);
    Serial.println(topic);

    const char* status = doc["status"];
    
    if (String(status) == "on")
    {
        Serial.println("led on");
        digitalWrite(LED_BUILTIN, LOW);
    }
    
    if (String(status) == "off")
    {
        Serial.println("led off");
        digitalWrite(LED_BUILTIN, HIGH);
    }
}

void setup() {
    Serial.begin(115200);
    Serial.println();
    WiFi.mode(WIFI_STA);
    WiFi.begin("众创空间", "zckj11081109");
    while (!WiFi.isConnected())
    {
        delay(100);
    }
    Serial.println(WiFi.localIP());

    pinMode(A0, INPUT);
    pinMode(LED_BUILTIN, OUTPUT);

    mqtt.setServer("iot.eclipse.org", 1883);
    mqtt.setCallback(mqtt_callback);
}

void loop() {
    if (!mqtt.connected()) {
        const char* clientID = String(ESP.getChipId(), HEX).c_str();
        mqtt.connect(clientID, NULL, NULL, "slxy/nodemcu/status", 0, 1, "offline");
        mqtt.publish("slxy/nodemcu/status", "online", true);
        mqtt.subscribe("slxy/light");
    }
    mqtt.loop();
    const size_t capacity = JSON_OBJECT_SIZE(1);
    DynamicJsonDocument doc(capacity);
    doc["voltage"] = (analogRead(A0) * 3.3) / 1024;//需要先将整数转为浮点数，再做除法
    String msg;
    serializeJson(doc, msg);
    mqtt.publish("slxy/voltage", msg.c_str());
    delay(1000);
}
